import axios from 'axios'
import { Modal, Message } from 'ant-design-vue'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { tansParams, blobValidate } from "@/utils/zzj";
import { saveAs } from 'file-saver'
let downloadLoadingInstance;

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // 跨域请求时发送cookies
  timeout: 5000, // 超时时间
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
})

// request 拦截器（发出请求前处理）
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    // console.log(config)
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    console.log(response.request)
    if(response.request.responseType ===  'blob' || response.request.responseType ===  'arraybuffer'){
      return response.data
    }
    const res = response.data
    // 状态码判定
    if (res.code !== 200) {
      Message.error(res.msg || 'Error', 3)
      // 50008: 非法令牌; 50012: 其他客户端登录; 50014: 令牌过期;
      if (res.code === 401) {
        Modal.warning({
          content: '您已注销，您可以取消以停留在此页，或重新登录', 
          title: '确认注销', 
          okText: '重新登录',
          cancelText: '取消',
          onOk() {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          }
        })
      }
      console.log(res)
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message.error(error.message, 3)
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download(url, params, filename) {
  downloadLoadingInstance = this.$message.loading('正在下载数据，请稍候', 0);
  return service.get(url, {
    params: params,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob'
  }).then(async (data) => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = rspObj.msg
      Message.error(errMsg);
    }
    setTimeout(downloadLoadingInstance, 50);
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')  
    setTimeout(downloadLoadingInstance, 50);
  })
}

export default service
